import api from '@/api';
import { useBaseInfoStore } from '@/store/modules/base-info.js';
import { mapState } from 'pinia';
import globalData from '@/plugins/data';
const baseInfoStore = useBaseInfoStore();

export default {
  data() {
    return {
      searchByKey: '',
      hideEmptyContent: '0',
      contentAnchor: globalData.contentAnchor
    };
  },
  mounted() {
    this.initSummaryComments();
  },
  computed: {
    ...mapState(useBaseInfoStore, ['baseInfo'])
  },
  updated() {
    this.$nextTick(() => {
      if (this.contentAnchor) {
        //意见滚动
        let scrollToComment = this.$refs[`opinionArea-${this.activeKey}`].scrollToComment({
          id: this.contentAnchor
        });
        if (scrollToComment) {
          this.contentAnchor = '';
        }
      }
    });
  },
  watch: {
    baseInfo(v) {
      console.log('baseInfo--->', v, this.baseInfo);
      if (v) {
        this.initSummaryComments();
      }
    }
  },
  methods: {
    initSummaryComments() {
      this.getSummaryComments(false, false, true);
      // this.getSummaryCommentsRelatedToMe();
    },
    commentParams({ relatedToMe = '0', tab, queryType }) {
      //queryType 0原转发意见和当前意见，1原转发意见， 2当前意见
      let params = {};
      if (this.baseInfo) {
        var zwIframe = this.baseInfo.zwIframe.mainbody;
        var affair = this.baseInfo.businessData.affair;
        params = {
          isHistory: 'false',
          ...tab.page,
          pageNo: tab.page.page,
          queryType: queryType || '0',
          forwardMember: this.baseInfo.businessData.summary?.forwardMember || '',
          replyCounts: '1',
          relatedToMe: relatedToMe,
          hideEmptyContent: this.hideEmptyContent,
          searchByKey: this.searchByKey,
          moduleId: affair.objectId,
          affairId: affair.id,
          moduleType: zwIframe.moduleType,
          offset: this.offset,
          limit: 10,
          ...(this.contentAnchor && {
            anchorCommentId: this.contentAnchor
          })
        };
        // if(isForward) {
        // params.forwardMember = this.baseInfo.businessData.summary.forwardMember;
        // }
      }
      return params;
    },
    initTab(tab) {
      //当前意见的翻页
      tab.page = { page: 1, pageSize: 20 };
    },
    //isAdd为加载更多，isForward为转发
    async getSummaryComments(isAdd, isForward, isInit) {
      if (!this.baseInfo) return;
      let pageInfo = {};
      //评论加载更多
      if (isForward) {
        if (isAdd) {
          this.forwardPageInfo.page++;
          this.forwardPageInfo.forWardIsLoading = true;
        } else {
          this.forwardPageInfo.page = 1;
        }
        pageInfo.page = {
          page: this.forwardPageInfo.page,
          pageSize: this.forwardPageInfo.pageSize
        };
      } else {
        if (isAdd) {
          this.tabs.page.page++;
          this.tabs.isLoading = true;
        } else {
          // this.tabs.list = [];
          // this.tabs.isEnd = false;
          this.initTab(this.tabs);
        }
        pageInfo = this.tabs;
      }
      let queryType = isInit ? '0' : (isForward ? '1' : '2');
      const res = await api.findSummaryComments(
        this.commentParams({ relatedToMe: '0', tab: pageInfo, queryType })
      );
      const {
        allCommentCountMap,
        relatedToMe,
        commentList,
        currentHasNext,
        praiseToSumNum,
        commentForwardMap,
        allPraiseCountMap,
        forwardHasNext
      } = res;
      if (isInit) {
        //初始化都执行
        this.commentForwardMap = commentForwardMap;
        this.forwardPraiseCountMap = allPraiseCountMap;
        this.fixComment(commentList);
        this.tabs.list = commentList;
        this.hasLoadMore(forwardHasNext, currentHasNext);
      } else if (isForward) {
        //如果是转发
        if (isAdd) {
          for (let forwardItem in commentForwardMap) {
            const forwardList = commentForwardMap[forwardItem][0];
            if (this.commentForwardMap[forwardItem]) {
              this.commentForwardMap[forwardItem][0] =
                this.commentForwardMap[forwardItem][0].concat(forwardList);
            } else {
              this.commentForwardMap[forwardItem] = {};
              this.commentForwardMap[forwardItem][0] = forwardList;
            }
          }
          this.hasLoadMore(forwardHasNext, null);
        } else {
          this.commentForwardMap = commentForwardMap;
        }
        this.forwardPageInfo.forWardIsLoading = false;
        this.forwardPraiseCountMap = allPraiseCountMap;
      } else if (!isForward) {
        this.fixComment(commentList);
        if (isAdd) {
          this.tabs.list = this.tabs.list.concat(commentList);
        } else {
          this.tabs.list = commentList;
        }
        this.tabs.isLoading = false;
        this.hasLoadMore(null, currentHasNext);
      }
      this.allCommentCountMap = allCommentCountMap;
      this.relatedAndPraise.relatedToMe = relatedToMe;
      this.relatedAndPraise.praiseToSumNum = praiseToSumNum;
      if (this.commentForwardMap){
        let values = Object.values(this.commentForwardMap);
        values.forEach(forwardTimes=>{
          let commentList = Object.values(forwardTimes);
          commentList.forEach(list=>this.fixComment(list,true))
        })
        
      }

      //更新打印
      baseInfoStore.$patch((state) => {
        state.print.commentData = {
          comments: this.tabs.list,
          forwardNum: 0,
          commentTotal: allCommentCountMap[0] || 0,
          praiseTotal: praiseToSumNum,
          relatedToMe: relatedToMe
        };
      });
      
      
    },
    async getSummaryCommentsRelatedToMe(isAdd) {
      if (!this.baseInfo) return;
      if (!this.tabs.isEnd && isAdd) {
        this.tabs.page = this.tabs.page + 1;
      } else {
        // this.tabs.list = [];
        // this.tabs.isEnd = false;
        this.initTab(this.tabs);
      }
      this.tabs.isLoading = true;
      let queryType = "2";
      const result = await api.findSummaryComments(this.commentParams({ relatedToMe: '1', tab: this.tabs, queryType }));
      const { allCommentCountMap, commentList, relatedToMe, currentHasNext, praiseToSumNum } =result;
      this.fixComment(commentList);
      this.tabs.isLoading = false;
      this.allCommentCountMap = allCommentCountMap;
      this.relatedAndPraise.relatedToMe = relatedToMe;
      this.relatedAndPraise.praiseToSumNum = praiseToSumNum;
      if (isAdd) {
        this.tabs.list = this.tabs.list.concat(commentList);
      } else {
        this.tabs.list = commentList;
      }
      this.hasLoadMore(null, currentHasNext);
    },
    updateList(isAdd = false, isForward = false) {
      if (this.activeKey == 1 || isForward) {
        //第二个参数用于是否是更新当前意见区，跟转发做区分
        this.getSummaryComments(isAdd, isForward);
      } else {
        this.getSummaryCommentsRelatedToMe(isAdd, isForward);
      }
    },
    fixComment(commentList,forward=false) {
      if (!commentList) {
        return;
      }
      commentList.forEach((comment) => {
        if (comment.attachList) {
          comment.attFileDomain = comment.attachList.filter((att) => att.type === '0');
          comment.assDocDomain = comment.attachList.filter((att) => att.type !== '0');
        }
        //转发不显示日志图标
        if (forward) {
          comment.hasWfOperation = false;
        }
        //智能审核相关处理
        if (comment.subType === '1') {
          comment.canPraise = false;
          comment.canReply = false;
          comment.readOnly = true;
          comment.avatarImageUrl = `${_ctxPath}/common/workflow/images/node_SuperNodePic.png`;
        }
        if (comment.children) {
          this.fixComment(comment.children);
        }
      });
    },
    //是否来自转发
    addNextPageList(isForward) {
      this.updateList(true, isForward);
    },
    //处理是否有加载更多
    hasLoadMore(forwardHasNext, currentHasNext) {
      if (forwardHasNext === 'false') {
        this.forwardPageInfo.forWardIsEnd = true;
      }else if(forwardHasNext === 'true') {
        this.forwardPageInfo.forWardIsEnd = false;
      }
      if (currentHasNext === 'false') {
        this.tabs.isEnd = true;
      }else if(currentHasNext === 'true') {
        this.tabs.isEnd = false;
      }
    }
  }
};
